import { constantRoutes } from '@/router'
// import serviceMap from '@/serviceMap'
import Layout from '@/layout'
import Layout2 from '@/layout2'
import store from '@/store'
// import customRoutes from './customRoutes'
import { queryMenuListApi } from '@/api/system/menu'
import i18n from '@/locales'
// import merchantDevRoutes from './devRoutes/merchant'
// import fundsDevRoutes from './devRoutes/funds'

function hasPermission(roles, route) {
	if (route.meta && route.meta.roles) {
		return roles.some((role) => route.meta.roles.includes(role))
	} else {
		return true
	}
}

export function filterAsyncRoutes(routes, roles) {
	const res = []

	routes.forEach((route) => {
		const tmp = { ...route }
		if (hasPermission(roles, tmp)) {
			if (tmp.children) {
				tmp.children = filterAsyncRoutes(tmp.children, roles)
			}
			res.push(tmp)
		}
	})
	return res
}

const state = {
	routes: [],
	addRoutes: [],
	menus: [],
	userBtns: [],
	nowRoute: '2',
	currentRoutes: {}
}

const mutations = {
	SET_ROUTES: (state, value) => {
		state.addRoutes = value.asyncRouterMap
		state.routes = constantRoutes.concat(value.asyncRouterMap)
	},
	SET_MENUS: (state, value) => {
		state.menus = value
	},
	CLEAR_ROUTES: (state) => {
		state.addRoutes = []
		state.userBtns = []
	},
	SET_NOWROUTE: (state, value) => {
		state.nowRoute = value
	},
	SET_CURRENT_ROUTES: (state, routes) => {
		state.currentRoutes = routes
	},
	SET_USER_BTNS: (state, idList) => {
		state.userBtns = idList
	}
}

const sortRoutes = (routes) => {
	routes.forEach((route) => {
		routes.sort((a, b) => a.orderNum * 1 - b.orderNum * 1)
		if (
			route.children !== null &&
			route.children &&
			route.children.length
		) {
			route.children = sortRoutes(route.children)
		}
	})
	return routes
}

const actions = {
	getMenus({ commit }) {
		return new Promise((resolve, reject) => {
			queryMenuListApi({ permissionDisplay: 1 })
				.then(({ data }) => {
					commit('SET_MENUS', data)
					resolve(data)
				})
				.catch((err) => reject(err))
		})
	},
	generateRoutes({ commit }, roles) {
		console.time('generateRoutes')
		return new Promise((resolve) => {
			// 开发新页面，在菜单管理中增加对应页面配置  /system/authorityManage/menuManage
			let asyncRouterMap = JSON.stringify(roles)
			const buttonList = []
			// asyncRouterMap = filterConstRouter(JSON.parse(asyncRouterMap), buttonList)
			asyncRouterMap = filterAsyncRouter(
				JSON.parse(asyncRouterMap),
				buttonList
			)

			sortRoutes(asyncRouterMap)
			const rootRoutes = []

			const rootRoute = asyncRouterMap[0]
			if (rootRoute && rootRoute.children && rootRoute.children.length) {
				rootRoutes.push({
					path: '/',
					redirect:
						rootRoute.children &&
						rootRoute.children[0].children[0].path
				})
			} else {
				rootRoutes.push({
					path: '/'
					// redirect: rootRoute.path
				})
			}
			asyncRouterMap = asyncRouterMap.concat(rootRoutes)
			const id = window.sessionStorage.getItem('activeId')
			id && store.dispatch('permission/setNowroute', id)

			const filterBtns = (buttonList) => {
				const arr = buttonList.map((item) => item.id)
				commit('SET_USER_BTNS', arr)
			}

			filterBtns(buttonList)

			commit('SET_ROUTES', {
				asyncRouterMap
			})

			resolve(asyncRouterMap)
			console.timeEnd('generateRoutes')
		})
	},
	clearRoutes({ commit }) {
		commit('CLEAR_ROUTES')
	},
	setNowroute({ commit }, id) {
		commit('SET_NOWROUTE', id)
	}
}

// 路由鉴权
function filterAsyncRouter(asyncRouterMap, buttonList) {
	// const menus = state.menus
	const arr = []
	asyncRouterMap.forEach((route) => {
		// 菜单
		if (route.type === '0') {
			const routeName = i18n.te(route.permissionName)
				? i18n.t(route.permissionName)
				: route.permissionName
			Object.assign(route, {
				path: route.component || route.path,
				name: routeName,
				hidden: +route.visible === 0,
				meta: {
					title: routeName,
					icon: route.icon,
					noCache: !route.isCache
				},
				show: true,
				checked: false
			})
			// 菜单层级
			if (route.level === 3) {
				const fullPath = route.path
				const pos = fullPath.lastIndexOf('/')
				const filePath = fullPath.substr(pos + 1)
				route.name = filePath
				route.component = (resolve) =>
					require(['@/views' + route.path + '/index'], resolve)
				buttonList.push({ id: route.id })
				route.bottom &&
					route.bottom.length &&
					buttonList.push(...route.bottom)
			} else {
				// 1： 一级目录层级  2： 二级目录层级
				route.level === 1
					? (route.component = Layout)
					: (route.component = Layout2)
			}

			arr.push(route)

			if (
				route.children !== null &&
				route.children &&
				route.children.length
			) {
				route.children = filterAsyncRouter(route.children, buttonList)
			}
		} else if (route.type == 1) {
			buttonList.push({ id: route.id })
		}
	})
	return arr
}

// function arrayToTree(data, pid) {
// 	const tree = []
// 	let temp
// 	for (var i = 0; i < data.length; i++) {
// 		if (data[i].parentId === pid) {
// 			const route = data[i]
// 			if (!route.path) {
// 				route.path = `/${data[i].id}`
// 			}
// 			route.name = route.title
// 			route.meta = {
// 				title: route.title,
// 				icon: route.icon
// 			}
// 			route.show = true
// 			route.checked = false
// 			if (route.level) {
// 				route.level === '1'
// 					? (route.component = Layout)
// 					: (route.component = Layout2)
// 			} else {
// 				route.component = (resolve) =>
// 					require(['@/views' + route.path + '/index'], resolve)
// 			}
// 			temp = arrayToTree(data, data[i].id)
// 			if (temp.length > 0) {
// 				route.children = temp
// 			}
// 			tree.push(route)
// 		}
// 	}

// 	return tree
// }

// function filterConstRouter() {
// 	console.time('arrayToTree')
// 	const routes = arrayToTree(serviceMap, '0')
// 	console.timeEnd('arrayToTree')
// 	return routes
// }

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
